/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package User;

import Bean.uploadBeanRemote;
import Objects.Album;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import javax.imageio.ImageIO;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.imgscalr.Scalr;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author ntfsbk
 */
@Controller
@RequestMapping("/upload")
public class uploadController {

    InitialContext context;
    uploadBeanRemote uploadBean;
    String folderPath = "/ImageFileData";

    @RequestMapping("/save")
    public void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("html/textplain");
        String pictureName = request.getParameter("pictureName");
        String pictureTag = request.getParameter("pictureTag");
        String albumName = request.getParameter("albumName");
        int flag = Integer.parseInt(request.getParameter("flag"));
        String name = request.getParameter("name");
        String link = folderPath + "/" + name;
        
        try {
            int imageId = uploadBean.getImageId(link);
            if (pictureName.equals("") == false) {
                uploadBean.updateImageName(pictureName, imageId);
            }
            if (pictureTag.equals("") == false) {
                uploadBean.updateImageTag(pictureTag, imageId);
            }
            if (flag == 0) {
                uploadBean.updateImageToExistAlbum(Integer.parseInt(albumName), imageId);
            } else {
                int userId = (Integer) request.getSession().getAttribute("userId");
                uploadBean.updateImageToNewAlbum(albumName, imageId, userId);
            }
//            uploadBean.reset();    
            response.getWriter().write("true");
        } catch (Exception e) {
//            uploadBean.reset();
            e.printStackTrace();
            response.getWriter().write("false");
        }
    }

    @RequestMapping("/startupload")
    public ModelAndView hello(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView view = new ModelAndView("upload");
               
        context = new InitialContext();
        uploadBean = (uploadBeanRemote) context.lookup("uploadBean");
        
        HttpSession session = request.getSession();
        int userId = (Integer) session.getAttribute("userId");
        List<Album> albums = uploadBean.getListAlbum(userId);
        view.addObject("albums", albums);
        String newNameAlbum = getNewNameAlbum();
        view.addObject("newAlbum", newNameAlbum);
        String userName=(String)session.getAttribute("userName");
        view.addObject("userName", userName);
        view.addObject("userId", userId);
        return view;
    }

    @RequestMapping(method = RequestMethod.POST)
    public void up(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
        }
        
        PrintWriter writer = response.getWriter();
        response.setContentType("application/json");
        JSONArray json = new JSONArray();
        try {
            ServletContext sc = request.getSession().getServletContext();
            File fileUploadPath = new File(sc.getRealPath(folderPath));

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> multipartFiles = multipartRequest.getFiles("files");

            for (MultipartFile multipartFile : multipartFiles) {
                String temName = multipartFile.getOriginalFilename();
                String suf = getSuffix(temName);
                int userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
                String fileName = uploadBean.insertNewImage(folderPath, userId, suf);

                File file = new File(fileUploadPath, fileName);
                multipartFile.transferTo(file);

                JSONObject jsono = new JSONObject();
                jsono.put("name", fileName);
                jsono.put("size", multipartFile.getSize());
                jsono.put("url", sc.getContextPath() + "/upload.htm?getfile=" + fileName);
                jsono.put("thumbnail_url", sc.getContextPath() + "/upload.htm?getthumb=" + fileName);
                jsono.put("delete_url", sc.getContextPath() + "/upload.htm?delfile=" + fileName);
                jsono.put("delete_type", "GET");
                json.put(jsono);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            writer.write(json.toString());
            writer.close();
        }
    }

    @RequestMapping(method = RequestMethod.GET)
    public void down(HttpServletRequest request, HttpServletResponse response) throws Exception {
            
        ServletContext sc = request.getSession().getServletContext();
        File fileUploadPath = new File(sc.getRealPath(folderPath));

        if (request.getParameter("getfile") != null
                && !request.getParameter("getfile").isEmpty()) {

            File file = new File(fileUploadPath,
                    request.getParameter("getfile"));
            if (file.exists()) {
                int bytes = 0;
                ServletOutputStream op = response.getOutputStream();

                response.setContentType(getMimeType(file));
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

                byte[] bbuf = new byte[1024];
                DataInputStream in = new DataInputStream(new FileInputStream(file));

                while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                    op.write(bbuf, 0, bytes);
                }

                in.close();
                op.flush();
                op.close();
            }
        } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
            File file = new File(fileUploadPath, request.getParameter("delfile"));
            if (file.exists()) {
                String fileName = folderPath + "/" + request.getParameter("delfile");
                uploadBean.deleteImage(fileName);
                file.delete(); // TODO:check and report success
            }
        } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
            File file = new File(fileUploadPath, request.getParameter("getthumb"));
            if (file.exists()) {
                String mimetype = getMimeType(file);
                if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("gif")) {
                    BufferedImage im = ImageIO.read(file);
                    if (im != null) {
                        BufferedImage thumb = Scalr.resize(im, 75);
                        ByteArrayOutputStream os = new ByteArrayOutputStream();
                        if (mimetype.endsWith("png")) {
                            ImageIO.write(thumb, "PNG", os);
                            response.setContentType("image/png");
                        } else if (mimetype.endsWith("jpeg")) {
                            ImageIO.write(thumb, "jpg", os);
                            response.setContentType("image/jpeg");
                        } else {
                            ImageIO.write(thumb, "GIF", os);
                            response.setContentType("image/gif");
                        }
                        ServletOutputStream srvos = response.getOutputStream();
                        response.setContentLength(os.size());
                        response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                        os.writeTo(srvos);
                        srvos.flush();
                        srvos.close();
                    }
                }
            } // TODO: check and report success
        } else {
            PrintWriter writer = response.getWriter();
            writer.write("call POST with multipart form data");
        }
    }

    private String getMimeType(File file) {
        String mimetype = "";
        if (file.exists()) {
//            URLConnection uc = new URL("file://" + file.getAbsolutePath()).openConnection();
//            String mimetype = uc.getContentType();
//            MimetypesFIleTypeMap gives PNG as application/octet-stream, but it seems so does URLConnection
//            have to make dirty workaround
            if (getSuffix(file.getName()).equalsIgnoreCase("png")) {
                mimetype = "image/png";
            } else {
                javax.activation.MimetypesFileTypeMap mtMap = new javax.activation.MimetypesFileTypeMap();
                mimetype = mtMap.getContentType(file);
            }
        }
        System.out.println("mimetype: " + mimetype);
        return mimetype;
    }

    private String getSuffix(String filename) {
        String suffix = "";
        int pos = filename.lastIndexOf('.');
        if (pos > 0 && pos < filename.length() - 1) {
            suffix = filename.substring(pos + 1);
        }
        System.out.println("suffix: " + suffix);
        return suffix;
    }

//    private String getpostfix(String filename) {
//        String suffix = "";
//        int pos = filename.lastIndexOf('.');
//        if (pos > 0 && pos < filename.length() - 1) {
//            suffix = filename.substring(0, pos);
//        }
//        System.out.println("suffix: " + suffix);
//        return suffix;
//    }
    private String getNewNameAlbum() {
        Date calendar = new Date();
        int tempMonth = calendar.getMonth();
        String month = "";
        switch (tempMonth) {
            case 1:
                month = "January";
            case 2:
                month = "February";
            case 3:
                month = "March";
            case 4:
                month = "April";
            case 5:
                month = "May";
            case 6:
                month = "June";
            case 7:
                month = "July";
            case 8:
                month = "August";
            case 9:
                month = "September";
            case 10:
                month = "October";
            case 11:
                month = "November";
            case 12:
                month = "December";
        }
        int date = calendar.getDate();
        int year = calendar.getYear() + 1900;

        String nameAlbum = month + " " + date + ", " + year;
        return nameAlbum;
    }
}
